package com.kirayous.gulimall.ware.listener;

import com.kirayous.common.to.mq.OrderTo;
import com.kirayous.common.to.mq.StockLockedTo;
import com.kirayous.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;



    //注意，这里虽然使用同一个队列，但是会根据传进的消息类型而选择不同的方法
    //例如消息队列传一个StockLockedTo对象，那么会被分发到handleStockLockedRelease这个方法
    // 如果消息队列传递OrderTo对象，那么会被分发到handleOrderCloseRelease方法
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        //这个是等时间过期自动触发的，也就是说这个是从延迟队列的来的消息
        System.out.println("收到解锁库存的消息...");
        try{
            //当前消息是否被第二次及以后（重新）派发过来了。
//            Boolean redelivered = message.getMessageProperties().getRedelivered();
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
    //这个是订单超时的时候，订单发送的消息，让库存主动解锁，这是为了双重保险
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("订单关闭准备解锁库存...");
        try{
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }

}
